package com.itheima.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    //登录
    @Override
    public ResultInfo login(String phone, String code) {
        String scode = (String) redisTemplate.opsForValue().get("Msg" + phone);
        if (!StrUtil.equals(scode,code)) {
            throw new CustomException("验证码不一致或未在规定时间内填写...");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User user = userMapper.selectOne(wrapper);
        if (user==null) {
            User user1=new User();
            user1.setPhone(phone);
            user1.setStatus(1);
            userMapper.insert(user1);
            return ResultInfo.success(user1);
        }else if(user.getStatus()!=1){
            throw new CustomException("用户已被禁用，请联系企业客服");
        }
        return ResultInfo.success(user);
    }
}
